<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <a-select placeholder="请选择" default-value="" v-model="model.type">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="综合">综合</a-select-option>
                <a-select-option value="技术">技术</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="category">
              <a-select placeholder="请选择" default-value="" v-model="model.category">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="清标检查">清标检查</a-select-option>
                <a-select-option value="初步审查">初步审查</a-select-option>
                <a-select-option value="详细审查">详细审查</a-select-option>
                <a-select-option value="清标评审">清标评审</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="标段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bidSectionIds">
              <!-- <j-checkbox v-model="model.bidSectionIds" :options="exSectionOptions" /> -->
              <a-radio-group v-model="model.bidSectionIds" :options="exSectionOptions" @change="bidSectionChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联标段内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
              <a-table
                ref="table"
                size="middle"
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="false"
                :loading="loading"
                :expandedRowKeys="expandedRowKeys"
                @change="handleTableChange"
                @expand="handleExpand"
                :defaultExpandAllRows="true"
                :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
                v-bind="tableProps"
              >
              </a-table>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="启用状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <j-switch v-model="model.status"></j-switch>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="24">
            <a-form-model-item label="审查项" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reviewItem">
              <a-textarea v-model="model.reviewItem" rows="4" placeholder="请输入审查项" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="审查标准" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reviewStandard">
              <a-textarea v-model="model.reviewStandard" rows="4" placeholder="请输入审查标准" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <smart-input style="margin-left: 90px" @input-processed="smartFill"></smart-input>
          </a-col>
          <a-col :span="24">
            <!-- {{ detailList }} -->
            <a-form-model-item label="审查项" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
              <a-table :columns="detailColumns" :dataSource="detailList" :pagination="false">
                <template
                  v-for="(col, i) in ['reviewItem', 'reviewStandard', 'remark']"
                  :slot="col"
                  slot-scope="text, record, index"
                >
                  <a-textarea
                    :key="col"
                    v-if="record.editable"
                    style="margin: -5px 0"
                    :value="text"
                    :placeholder="columns[i].title"
                    @change="(e) => handleChange(e.target.value, record.id, col)"
                    rows="4"
                  />
                  <template v-else>{{ text }}</template>
                </template>
                <template slot="operation" slot-scope="text, record, index">
                  <template v-if="record.editable">
                    <span v-if="record.isNew">
                      <a @click="saveRow(record.id)">添加</a>
                      <a-divider type="vertical" />
                      <a-popconfirm title="是否要删除此行？" @confirm="remove(record.id)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                    <span v-else>
                      <a @click="saveRow(record.id)">保存</a>
                      <a-divider type="vertical" />
                      <a @click="cancel(record.id)">取消</a>
                    </span>
                  </template>
                  <span v-else>
                    <a @click="toggle(record.id)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="是否要删除此行？" @confirm="remove(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </a-table>
              <a-button
                style="width: 100%; margin-top: 16px; margin-bottom: 8px"
                type="dashed"
                icon="plus"
                @click="newMember"
                >新增项</a-button
              >
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { httpAction, getAction } from '@/api/manage'
import { randomUUID } from '@/utils/util'
import SmartInput from '@views/exZbwj/modules/smartInput.vue'
export default {
  name: 'ExZbwjConformanceReviewForm',
  mixins: [JeecgListMixin],
  components: { SmartInput },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      model: {},
      confirmLoading: false,
      validatorRules: {
        name: [{ required: true, message: '请输入名称!' }],
        type: [{ required: true, message: '请选择类别!' }],
        category: [{ required: true, message: '请选择分类!' }],
      },
      exSectionOptions: [],
      url: {
        add: '/exTenderFile/exZbwjConformanceReview/add',
        edit: '/exTenderFile/exZbwjConformanceReview/edit',
        queryById: '/exTenderFile/exZbwjConformanceReview/queryById',
        exZbwjConformanceReviewBidDetail: {
          list: '/exTenderFile/exZbwjConformanceReview/queryExZbwjConformanceReviewBidDetailByMainId',
        },
        exZbwjConformanceReviewDetail: {
          list: '/exTenderFile/exZbwjConformanceReview/queryExZbwjConformanceReviewDetailByMainId',
        },
        exSection: {
          list: '/exProject/exProject/queryExSectionByMainId',
        },
        chapterList: '/exTenderFile/chapter/rootList',
        getChildListBatch: '/exTenderFile/chapter/getChildListBatch',
      },
      // 表头
      columns: [
        {
          title: ' ',
          align: 'left',
          dataIndex: 'name',
        },
        {
          title: ' ',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      expandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'pid',
      projectInfo: {},

      // table
      detailColumns: [
        // {
        //   title: 'ID',
        //   dataIndex: 'id',
        //   key: 'id',
        //   width: '5%',
        // },
        {
          title: '审查项',
          dataIndex: 'reviewItem',
          key: 'reviewItem',
          width: '30%',
          scopedSlots: { customRender: 'reviewItem' },
        },
        {
          title: '审查标准',
          dataIndex: 'reviewStandard',
          key: 'reviewStandard',
          width: '60%',
          scopedSlots: { customRender: 'reviewStandard' },
        },
        // {
        //   title: '备注',
        //   dataIndex: 'remark',
        //   key: 'remark',
        //   width: '40%',
        //   scopedSlots: { customRender: 'remark' },
        // },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      detailList: [
        // {
        //   id: '1',
        //   reviewItem: '审查项1',
        //   reviewStandard: '001',
        //   remark: '备注1',
        //   editable: false,
        // },
      ],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  watch: {
    'model.projectId'(newVal) {
      if (newVal != '' && newVal != undefined) {
        this.getExSectionList(newVal)
      }
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    smartFill($event) {
      $event?.forEach((v) => {
        this.detailList.push({
          id: randomUUID(),
          reviewItem: v[0],
          reviewStandard: v[1],
          remark: '',
          editable: true,
          isNew: true,
        })
      })
    },
    newMember() {
      this.detailList.push({
        id: randomUUID(),
        reviewItem: '',
        reviewStandard: '',
        remark: '',
        editable: true,
        isNew: true,
      })
    },
    remove(key) {
      const newData = this.detailList.filter((item) => item.id !== key)
      this.detailList = newData
    },
    saveRow(key) {
      let target = this.detailList.filter((item) => item.id === key)[0]
      target.editable = false
      target.isNew = false
    },
    toggle(key) {
      let target = this.detailList.filter((item) => item.id === key)[0]
      target.editable = !target.editable
    },
    getRowByKey(key, newData) {
      const data = this.detailList
      return (newData || data).filter((item) => item.id === key)[0]
    },
    cancel(key) {
      let target = this.detailList.filter((item) => item.id === key)[0]
      target.editable = false
    },
    handleChange(value, key, column) {
      const newData = [...this.detailList]
      const target = newData.filter((item) => key === item.id)[0]
      if (target) {
        target[column] = value
        this.detailList = newData
      }
    },

    add(project) {
      this.edit(this.modelDefault)
      this.projectInfo = project
      this.model.projectId = this.projectInfo.projectId
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.loadCategoryList(this.model.bidSectionIds)
      this.getReviewBidDetail(this.model.id)
      this.getReviewDetail(this.model.id)
    },
    getReviewBidDetail(reviewId) {
      if (!reviewId) {
        return
      }
      //获取已选择的 关联标段内容
      var that = this
      that.selectedRowKeys = []
      getAction(that.url.exZbwjConformanceReviewBidDetail.list, { id: reviewId })
        .then((res) => {
          if (res.success) {
            res.result.forEach((row) => {
              that.selectedRowKeys.push(row.categoryId)
            })
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    getReviewDetail(reviewId) {
      if (!reviewId) {
        return
      }
      //获取已选择的 关联标段内容
      var that = this
      that.detailList = []
      getAction(that.url.exZbwjConformanceReviewDetail.list, { id: reviewId })
        .then((res) => {
          if (res.success) {
            res.result.forEach((item) => {
              item.editable = false
            })
            that.detailList = res.result
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          var chapterIds = that.selectedRowKeys
          that.model.exZbwjConformanceReviewBidDetailList = []
          that.model.exZbwjConformanceReviewDetailList = that.detailList
          that.model.exZbwjConformanceReviewDetailList.forEach((item) => {
            item.id = ''
          })
          chapterIds.forEach((item) => {
            that.model.exZbwjConformanceReviewBidDetailList.push({ categoryId: item })
          })
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    getExSectionList(projectId) {
      //获取标段列表
      var that = this
      getAction(this.url.exSection.list, { id: projectId })
        .then((res) => {
          if (res.success) {
            that.exSectionOptions = []
            that.exSectionDataSource = res.result
            that.exSectionDataSource.forEach((row) => {
              that.exSectionOptions.push({ label: row.bidSectionName, value: row.id })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    bidSectionChange(e) {
      var sectionId = e.target.value
      this.loadCategoryList(sectionId)
    },
    loadCategoryList(sectionId) {
      if (this.model.projectId == '' || sectionId == '' || sectionId == undefined) {
        return
      }
      this.loading = true
      let params = {}
      params.projectId = this.model.projectId
      params.sectionId = sectionId
      return new Promise((resolve) => {
        getAction(this.url.chapterList, params)
          .then((res) => {
            if (res.success) {
              let result = res.result
              if (Number(result.total) > 0) {
                this.ipagination.total = Number(result.total)
                this.dataSource = this.getDataByResult(res.result.records)
                this.expandedRowKeys = res.result.records.map((e) => e.id)
                //update--begin--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
                return this.loadDataByExpandedRows(this.dataSource)
                //update--end--autor:lvdandan-----date:20201204------for：JT-31 删除成功后默认展开已展开信息
              } else {
                this.ipagination.total = 0
                this.dataSource = []
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = (list) => {
              if (list) {
                list.forEach((data) => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getDataByResult(result) {
      if (result && result.length > 0) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams() //查询条件
          params[this.pidField] = record.id
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result && res.result.length > 0) {
                record.children = this.getDataByResult(res.result)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    loadData(arg) {},
  },
}
</script>

<style scoped></style>
